﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Manager;
using Manager.CustomerHelper;
using ExtAspNet;
using System.IO;
using System.Data.OleDb;
using System.Data;
namespace HealthSystem
{
    public class BasePage : System.Web.UI.Page
    {
        public BasePage()
        {
            try
            {
                var result = User.Identity.IsAuthenticated;
                if (!result)
                {
                    HttpContext.Current.Response.Redirect("~/index.html");
                }
            }
            catch
            {
                HttpContext.Current.Server.Transfer("~/index.html");
            }
        }
        private MenuConfigManager _configBLL = null;
        private ProfileComm _cutomerProfile;
        protected ProfileComm CustomerProfile
        {
            get
            {
                if (_cutomerProfile == null)
                    return HttpContext.Current.Profile as ProfileComm;
                else
                    return _cutomerProfile;
            }
            set
            {
                _cutomerProfile = value;
            }
        }
        protected MenuConfigManager configBLL
        {
            get
            {
                if (_configBLL == null)
                    return new MenuConfigManager();
                else
                    return _configBLL;
            }
        }
        public static string noPowerUrl
        {
            get
            {
                return "~/NoPower.htm";
            }
        }
        protected void NoPowerPageShow()
        {
            HttpContext.Current.Response.Redirect(noPowerUrl);
        }
        #region static readonly

        //private static readonly log4net.ILog logger = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

        // Session key
        //private static readonly string SK_ONLINE_UPDATE_TIME = "OnlineUpdateTime";
        //private static readonly string SK_USER_ROLE_ID = "UserRoleId";

        //private static readonly string CHECK_POWER_FAIL_PAGE_MESSAGE = "您无权访问此页面！";
        private static readonly string CHECK_POWER_FAIL_ACTION_MESSAGE = "您无权进行此操作！";


        #endregion

        #region Module

        /// <summary>
        /// 本页面属于哪个模块
        /// </summary>
        public virtual ModuleType Module
        {
            get
            {
                return ModuleType.None;
            }
        }

        #endregion

        #region OnInit
        private bool IsSystemTheme(string themeName)
        {
            string[] themes = Enum.GetNames(typeof(Theme));
            foreach (string theme in themes)
            {
                if (theme.ToLower() == themeName)
                {
                    return true;
                }
            }
            return false;
        }
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);

            if (!CheckPowerCanRead())
            {
                CheckPowerFailWithPage();
                return;
            }
            if (!IsPostBack)
            {
                if (PageManager.Instance != null)
                {
                    string themeCookie = "first";
                    if (themeCookie != null)
                    {
                        string themValue = themeCookie;
                        if (IsSystemTheme(themValue))
                        {
                            PageManager.Instance.Theme = (Theme)Enum.Parse(typeof(Theme), themValue, true);
                        }
                        else
                        {
                            PageManager.Instance.CustomTheme = themValue;
                        }
                    }
                }
            }

            //UpdateOnlineUser(User.Identity.Name);

            // 设置页面标题
            //Page.Title = XConfigHelper.Title;
        }

        #endregion

        //protected string GetSortExpression<T>(Grid grid, T schema)
        //{
        //    GridColumn column = grid.Columns[grid.SortColumnIndex];
        //    string columnName = GetTableColumnName(schema, column.SortField);
        //    return String.Format("{0} {1}", columnName, grid.SortDirection);
        //}

        //protected string GetTableColumnName<T>(T table, string propertyName)
        //{
        //    PropertyInfo pi = typeof(T).get;
        //    foreach (PropertyInfo column in table.Columns)
        //    {
        //        if (column.PropertyName == propertyName)
        //        {
        //            return column.ColumnName;
        //        }
        //    }
        //    return String.Empty;
        //}
        #region GetQueryValue/GetQueryIntValue

        /// <summary>
        /// 获取查询字符串中的参数值
        /// </summary>
        protected string GetQueryValue(string queryKey)
        {
            return Request.QueryString[queryKey];
        }


        /// <summary>
        /// 获取查询字符串中的参数值
        /// </summary>
        protected int GetQueryIntValue(string queryKey)
        {
            int queryIntValue = -1;
            try
            {
                queryIntValue = Convert.ToInt32(Request.QueryString[queryKey]);
            }
            catch (Exception)
            {
                // TODO
            }

            return queryIntValue;
        }

        #endregion

        #region PageIndex/TotalCount/PageSize

        /// <summary>
        /// 当前显示第几页（从1开始）
        /// </summary>
        protected int PageIndex
        {
            get
            {
                if (ViewState["PageIndex"] == null)
                {
                    ViewState["PageIndex"] = 1;
                }
                return Convert.ToInt32(ViewState["PageIndex"]);
            }
            set
            {
                ViewState["PageIndex"] = value;
            }
        }
        /// <summary>
        /// 总共多少条记录
        /// </summary>
        protected int TotalCount
        {
            get
            {
                if (ViewState["TotalCount"] == null)
                {
                    ViewState["TotalCount"] = 0;
                }
                return Convert.ToInt32(ViewState["TotalCount"]);
            }
            set
            {
                ViewState["TotalCount"] = value;
            }
        }

        /// <summary>
        /// 每页显示多少条记录
        /// </summary>
        protected int PageSize
        {
            get
            {
                if (ViewState["PageSize"] == null)
                {
                    //ViewState["PageSize"] = XConfigHelper.PageSize;
                    ViewState["PageSize"] = 30;
                }
                return Convert.ToInt32(ViewState["PageSize"]);
            }
            set
            {
                ViewState["PageSize"] = value;
            }
        }

        /// <summary>
        /// 总共有多少页
        /// </summary>
        protected int PageCount
        {
            get
            {
                if (ViewState["PageCount"] == null)
                {
                    ViewState["PageCount"] = 1;
                }
                return Convert.ToInt32(ViewState["PageCount"]);
            }
            set
            {
                ViewState["PageCount"] = value;
            }
        }

        /// <summary>
        /// 排序字段
        /// </summary>
        protected string SortField
        {
            get
            {
                if (ViewState["SortField"] == null)
                {
                    ViewState["SortField"] = "addtime";
                }
                return ViewState["SortField"].ToString();
            }
            set
            {
                ViewState["SortField"] = value;
            }
        }

        /// <summary>
        /// 排序方向
        /// </summary>
        protected string SortDirection
        {
            get
            {
                if (ViewState["SortDirection"] == null)
                {
                    ViewState["SortDirection"] = "desc";
                }
                return ViewState["SortDirection"].ToString();
            }
            set
            {
                ViewState["SortDirection"] = value;
            }
        }


        #endregion

        #region GetSortExpression/GetTableColumnName

        /// <summary>
        /// 获取表格选中项DataKeys的第一个值，并转化为整型列表
        /// </summary>
        /// <param name="grid"></param>
        /// <returns></returns>
        protected List<int> GetSelectedDataKeyIDs(Grid grid)
        {
            List<int> ids = new List<int>();
            foreach (int rowIndex in grid.SelectedRowIndexArray)
            {
                ids.Add(Convert.ToInt32(grid.DataKeys[rowIndex][0]));
            }

            return ids;
        }


        //protected string GetSortExpression(Grid grid, TableSchema.Table schema)
        //{
        //    GridColumn column = grid.Columns[grid.SortColumnIndex];
        //    string columnName = GetTableColumnName(schema, column.SortField);
        //    return String.Format("{0} {1}", columnName, grid.SortDirection);
        //}

        //protected string GetTableColumnName(TableSchema.Table table, string propertyName)
        //{
        //    foreach (TableSchema.TableColumn column in table.Columns)
        //    {
        //        if (column.PropertyName == propertyName)
        //        {
        //            return column.ColumnName;
        //        }
        //    }
        //    return String.Empty;
        //}

        #endregion

        #region ResolveDeleteButtonForGrid/ResolveDDL

        /// <summary>
        /// 为删除Grid中选中项的按钮添加提示信息
        /// </summary>
        /// <param name="btn"></param>
        /// <param name="grid"></param>
        protected void ResolveDeleteButtonForGrid(ExtAspNet.Button btn, Grid grid)
        {
            ResolveDeleteButtonForGrid(btn, grid, "确定要删除选中的{0}项记录吗？");
        }

        protected void ResolveDeleteButtonForGrid(ExtAspNet.Button btn, Grid grid, string confirmTemplate)
        {
            ResolveDeleteButtonForGrid(btn, grid, "请至少应该选择一项记录！", confirmTemplate);
        }

        protected void ResolveDeleteButtonForGrid(ExtAspNet.Button btn, Grid grid, string noSelectionMessage, string confirmTemplate)
        {
            // 点击删除按钮时，至少选中一项
            btn.OnClientClick = grid.GetNoSelectionAlertInParentReference(noSelectionMessage);
            btn.ConfirmText = String.Format(confirmTemplate, "<span class=\"highlight\"><script>" + grid.GetSelectCountReference() + "</script></span>");
            btn.ConfirmTarget = Target.Top;
        }


        protected List<T> ResolveDDL<T>(List<T> mys) where T : CustomTree, ICloneable, new()
        {

            return ResolveDDL<T>(mys, -1, true);
        }

        protected List<T> ResolveDDL<T>(List<T> mys, int currentId) where T : CustomTree, ICloneable, new()
        {
            return ResolveDDL<T>(mys, currentId, true);
        }

        /// <summary>
        /// 将一个树型结构放在一个下列列表中可供选择
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="currentId"></param>
        /// <param name="mys"></param>
        protected List<T> ResolveDDL<T>(List<T> mys, int currentId, bool addRootNode) where T : CustomTree, ICloneable, new()
        {
            List<T> result = new List<T>();

            if (addRootNode)
            {
                // 添加根节点
                T root = new T();
                root.Title = "--根节点--";
                root.Id = 0;
                root.TreeLevel = 0;
                result.Add(root);
            }

            foreach (T my in mys)
            {
                T newT = (T)my.Clone();
                result.Add(newT);

                // 所有节点的TreeLevel加一
                if (addRootNode)
                {
                    newT.TreeLevel += 1;
                }
            }


            // currentId==-1表示当前节点不存在
            if (currentId != -1)
            {
                // 本节点不可点击（也就是说当前节点不可能是当前节点的父节点）
                // 并且本节点的所有子节点也不可点击，你想如果当前节点跑到子节点的子节点，那么这些子节点就从树上消失了
                bool startChileNode = false;
                int startTreeLevel = 0;
                foreach (T my in result)
                {
                    if (my.Id == currentId)
                    {
                        startTreeLevel = my.TreeLevel;
                        my.Enabled = false;
                        startChileNode = true;
                    }
                    else
                    {
                        if (startChileNode)
                        {
                            if (my.TreeLevel > startTreeLevel)
                            {
                                my.Enabled = false;
                            }
                            else
                            {
                                startChileNode = false;
                            }
                        }
                    }
                }
            }

            return result;
        }

        #endregion

        //#region UpdateOnlineUser/LoginOnlineUser/GetOnlineCount

        //protected void UpdateOnlineUser(string username)
        //{
        //    DateTime now = DateTime.Now;
        //    object lastUpdateTime = Session[SK_ONLINE_UPDATE_TIME];
        //    if (lastUpdateTime == null || (Convert.ToDateTime(lastUpdateTime).Subtract(now).TotalMinutes > 5))
        //    {
        //        // 记录本次更新时间
        //        Session[SK_ONLINE_UPDATE_TIME] = now;

        //        XOnline online = new Select().From<XOnline>()
        //              .Where(XOnline.UserNameColumn).IsEqualTo(username)
        //              .ExecuteSingle<XOnline>();

        //        if (online != null)
        //        {
        //            online.UpdateTime = now;
        //            online.Save();
        //        }
        //    }
        //}

        //protected void LoginOnlineUser(XUser user)
        //{
        //    XOnline online = new Select().From<XOnline>()
        //          .Where(XOnline.UserIdColumn).IsEqualTo(user.Id)
        //          .ExecuteSingle<XOnline>();

        //    // 如果不存在，就创建一条新的记录
        //    if (online == null)
        //    {
        //        online = new XOnline();
        //    }
        //    DateTime now = DateTime.Now;
        //    online.UserId = user.Id;
        //    online.UserName = user.Name;
        //    online.UserRealName = user.RealName;
        //    online.IPAdddress = Request.UserHostAddress;
        //    online.LoginTime = now;
        //    online.UpdateTime = now;
        //    online.Save();

        //    // 记录本次更新时间
        //    Session[SK_ONLINE_UPDATE_TIME] = now;

        //    //// 保存用户的角色ID（如果未定义，则为-1）
        //    //Session[SK_USER_ROLE_ID] = -1;
        //    //if (user.RoleId.HasValue)
        //    //{
        //    //    Session[SK_USER_ROLE_ID] = user.RoleId.Value;
        //    //}

        //}

        //protected int GetOnlineCount()
        //{
        //    return new Select().From<XOnline>()
        //        .Where(XOnline.UpdateTimeColumn).IsGreaterThan(DateTime.Now.AddMinutes(-15))
        //        .GetRecordCount();
        //}

        //#endregion

        #region Module Power

        protected bool CheckPowerCanRead()
        {
            return CheckPower(ModulePowerType.CanRead);
        }

        protected bool CheckPowerNew()
        {
            return CheckPower(GetModulePowerType("New"));
        }

        protected bool CheckPowerEdit()
        {
            return CheckPower(GetModulePowerType("Edit"));
        }

        protected bool CheckPowerDelete()
        {
            return CheckPower(GetModulePowerType("Delete"));
        }
        protected bool CheckPowerShenHe()
        {
            return CheckPower(GetModulePowerType("ShenHe"));
        }
        protected bool CheckPowerSend()
        {
            return CheckPower(GetModulePowerType("Send"));
        }


        protected bool CheckPowerEditA()
        {
            return CheckPower(GetModulePowerType("EditA"));
        }

        protected bool CheckPowerNewA()
        {
            return CheckPower(GetModulePowerType("NewA"));
        }
        protected bool CheckPowerDeleteA()
        {
            return CheckPower(GetModulePowerType("DeleteA"));
        }
        protected bool CheckPowerAnnexA()
        {
            return CheckPower(GetModulePowerType("AnnexA"));
        }
        protected bool CheckPowerDownA()
        {
            return CheckPower(GetModulePowerType("DownA"));
        }
        protected bool CheckPowerFolderA()
        {
            return CheckPower(GetModulePowerType("FolderA"));
        }



        protected bool CheckPowerEditB()
        {
            return CheckPower(GetModulePowerType("EditB"));
        }

        protected bool CheckPowerNewB()
        {
            return CheckPower(GetModulePowerType("NewB"));
        }
        protected bool CheckPowerDeleteB()
        {
            return CheckPower(GetModulePowerType("DeleteB"));
        }
        protected bool CheckPowerAnnexB()
        {
            return CheckPower(GetModulePowerType("AnnexB"));
        }
        protected bool CheckPowerDownB()
        {
            return CheckPower(GetModulePowerType("DownB"));
        }
        protected bool CheckPowerFolderB()
        {
            return CheckPower(GetModulePowerType("FolderB"));
        }




        protected bool CheckPowerLend()
        {
            return CheckPower(GetModulePowerType("Lend"));
        }


        protected bool CheckPowerCaicui()
        {
            return CheckPower(GetModulePowerType("Caicui"));
        }


        protected bool CheckPowerCaigen()
        {
            return CheckPower(GetModulePowerType("Caigen"));
        }


        protected bool CheckPowerDown()
        {
            return CheckPower(GetModulePowerType("Down"));
        }

        protected bool CheckPowerGuest()
        {
            return CheckPower(GetModulePowerType("Guest"));
        }

        protected bool CheckPowerRestaurant()
        {
            return CheckPower(GetModulePowerType("Restaurant"));
        }

        protected bool CheckPowerMenuAdmin()
        {
            return CheckPower(GetModulePowerType("MenuAdmin"));
        }

        protected bool CheckPowerDutyCom()
        {
            return CheckPower(GetModulePowerType("DutyCom"));
        }

        protected bool CheckPowerDutyStone()
        {
            return CheckPower(GetModulePowerType("DutyStone"));
        }

        protected bool CheckPowerDutyRestaurant()
        {
            return CheckPower(GetModulePowerType("DutyRestaurant"));
        }

        protected bool CheckPowerTshow()
        {
            return CheckPower(GetModulePowerType("Tshow"));
        }
        protected bool CheckPowerAshow()
        {
            return CheckPower(GetModulePowerType("Ashow"));
        }


        private ModulePowerType GetModulePowerType(string powerTypeName)
        {
            return ModulePowerTypeHelper.String2Power(String.Format("{0}_{1}", ModuleTypeHelper.Module2String(Module), powerTypeName));
        }


        // http://blog.163.com/zjlovety@126/blog/static/224186242010070024282/
        // http://www.cnblogs.com/gaoshuai/articles/1863231.html
        protected bool CheckPower(ModulePowerType powerType)
        {
            // 如果此页面不属于任何一个模块，则放行
            if (Module == ModuleType.None)
            {
                return true;
            }

            // 查询一个未定义的权限，则拒绝
            if (powerType == ModulePowerType.None)
            {
                return false;
            }

            // 如果此用户还未定义角色，则拒绝
            int roleId = GetIdentityRoleId();
            if (roleId <= 0)
            {
                return false;
            }

            Dictionary<string, RoleModulePower> roleModuleDic = RoleModulePowerHelper.GetRoleModulePowerDic(roleId);
            string moduleTypeName = ModuleTypeHelper.Module2String(Module);
            RoleModulePower modulePower = roleModuleDic[moduleTypeName];

            bool power = false;
            switch (powerType)
            {
                case ModulePowerType.CanRead:
                    power = modulePower.CanRead;
                    break;
                //case ModulePowerType.CanAdd:
                //    power = modulePower.CanAdd;
                //    break;
                //case ModulePowerType.CanEdit:
                //    power = modulePower.CanEdit;
                //    break;
                //case ModulePowerType.CanDelete:
                //    power = modulePower.CanDelete;
                //    break;
                default:
                    string powerTypeName = ModulePowerTypeHelper.GetPowerTypeName(powerType, moduleTypeName);
                    if (!String.IsNullOrEmpty(powerTypeName))
                    {
                        power = modulePower.OtherPowers.Value<bool?>(powerTypeName) ?? false;
                    }
                    break;
            }

            return power;
        }


        protected int GetIdentityRoleId()
        {

            //FormsAuthenticationTicket ticket = ((FormsIdentity)User.Identity).Ticket;
            //return Convert.ToInt32(ticket.UserData);
            return Convert.ToInt32(CustomerProfile.RoleId);
        }


        #endregion

        #region Power UI

        protected void CheckPowerFailWithPage()
        {
            NoPowerPageShow();
            //Response.Write(CHECK_POWER_FAIL_PAGE_MESSAGE);
            //Response.End();
        }

        protected void CheckPowerFailWithButton(ExtAspNet.Button btn)
        {
            btn.Enabled = false;
            btn.ToolTip = CHECK_POWER_FAIL_ACTION_MESSAGE;
        }

        protected void CheckPowerFailWithLinkButtonField(ExtAspNet.Grid grid, string columnId)
        {
            ExtAspNet.LinkButtonField btn = grid.FindColumn(columnId) as ExtAspNet.LinkButtonField;
            btn.Enabled = false;
            btn.ToolTip = CHECK_POWER_FAIL_ACTION_MESSAGE;
        }

        protected void CheckPowerFailWithWindowField(ExtAspNet.Grid grid, string columnId)
        {
            ExtAspNet.WindowField btn = grid.FindColumn(columnId) as ExtAspNet.WindowField;
            btn.Enabled = false;
            btn.ToolTip = CHECK_POWER_FAIL_ACTION_MESSAGE;
        }

        protected void CheckPowerFailWithAlert()
        {
            PageContext.RegisterStartupScript(Alert.GetShowInTopReference(CHECK_POWER_FAIL_ACTION_MESSAGE));
        }

        #region Power Button

        protected void CheckPowerWithButton(ModulePowerType powerType, ExtAspNet.Button btn)
        {
            if (!CheckPower(powerType))
            {
                CheckPowerFailWithButton(btn);
            }
        }


        protected void CheckPowerNewWithButton(ExtAspNet.Button btn)
        {
            if (!CheckPowerNew())
            {
                CheckPowerFailWithButton(btn);
            }
        }

        protected void CheckPowerEditWithButton(ExtAspNet.Button btn)
        {
            if (!CheckPowerEdit())
            {
                CheckPowerFailWithButton(btn);
            }
        }

        protected void CheckPowerDeleteWithButton(ExtAspNet.Button btn)
        {
            if (!CheckPowerDelete())
            {
                CheckPowerFailWithButton(btn);
            }
        }



        protected void CheckPowerCaicuiWithButton(ExtAspNet.Button btn)
        {
            if (!CheckPowerCaicui())
            {
                CheckPowerFailWithButton(btn);
            }
        }


        protected void CheckPowerGuestWithButton(ExtAspNet.Button btn)
        {
            if (!CheckPowerGuest())
            {
                CheckPowerFailWithButton(btn);
            }
        }

        protected void CheckPowerRestaurantWithButton(ExtAspNet.Button btn)
        {
            if (!CheckPowerRestaurant())
            {
                CheckPowerFailWithButton(btn);
            }
        }

        protected void CheckPowerMenuAdminWithButton(ExtAspNet.Button btn)
        {
            if (!CheckPowerMenuAdmin())
            {
                CheckPowerFailWithButton(btn);
            }
        }


        protected void CheckPowerCaigenWithButton(ExtAspNet.Button btn)
        {
            if (!CheckPowerCaigen())
            {
                CheckPowerFailWithButton(btn);
            }
        }

        protected void CheckPowerDutyComWithButton(ExtAspNet.Button btn)
        {
            if (!CheckPowerDutyCom())
            {
                CheckPowerFailWithButton(btn);
            }
        }

        protected void CheckPowerDutyStoneWithButton(ExtAspNet.Button btn)
        {
            if (!CheckPowerDutyStone())
            {
                CheckPowerFailWithButton(btn);
            }
        }

        protected void CheckPowerDutyRestaurantWithButton(ExtAspNet.Button btn)
        {
            if (!CheckPowerDutyRestaurant())
            {
                CheckPowerFailWithButton(btn);
            }
        }


        protected void CheckPowerTshowWithButton(ExtAspNet.Button btn)
        {
            if (!CheckPowerTshow())
            {
                CheckPowerFailWithButton(btn);
            }
        }


        protected void CheckPowerAshowWithButton(ExtAspNet.Button btn)
        {
            if (!CheckPowerAshow())
            {
                CheckPowerFailWithButton(btn);
            }
        }


        #endregion

        #region Power Grid

        protected void CheckPowerDeleteWithLinkButtonField(ExtAspNet.Grid grid, string columnId)
        {
            if (!CheckPowerDelete())
            {
                CheckPowerFailWithLinkButtonField(grid, columnId);
            }
        }

        protected void CheckPowerEditWithLinkButtonField(ExtAspNet.Grid grid, string columnId)
        {
            if (!CheckPowerEdit())
            {
                CheckPowerFailWithLinkButtonField(grid, columnId);
            }
        }

        protected void CheckPowerWithLinkButtonField(ModulePowerType powerType, ExtAspNet.Grid grid, string columnId)
        {
            if (!CheckPower(powerType))
            {
                CheckPowerFailWithLinkButtonField(grid, columnId);
            }
        }


        protected void CheckPowerDeleteWithWindowField(ExtAspNet.Grid grid, string columnId)
        {
            if (!CheckPowerDelete())
            {
                CheckPowerFailWithWindowField(grid, columnId);
            }
        }


        protected void CheckPowerGuestWithWindowField(ExtAspNet.Grid grid, string columnId)
        {
            if (!CheckPowerGuest())
            {
                CheckPowerFailWithWindowField(grid, columnId);
            }
        }

        protected void CheckPowerRestaurantWithWindowField(ExtAspNet.Grid grid, string columnId)
        {
            if (!CheckPowerRestaurant())
            {
                CheckPowerFailWithWindowField(grid, columnId);
            }
        }


        protected void CheckPowerEditWithWindowField(ExtAspNet.Grid grid, string columnId)
        {
            if (!CheckPowerEdit())
            {
                CheckPowerFailWithWindowField(grid, columnId);
            }
        }
        protected void CheckPowerDownWithWindowField(ExtAspNet.Grid grid, string columnId)
        {
            if (!CheckPowerDown())
            {
                CheckPowerFailWithWindowField(grid, columnId);
            }
        }

        protected void CheckPowerNewWithWindowField(ExtAspNet.Grid grid, string columnId)
        {
            if (!CheckPowerNew())
            {
                CheckPowerFailWithWindowField(grid, columnId);
            }
        }

        protected void CheckPowerWithWindowField(ModulePowerType powerType, ExtAspNet.Grid grid, string columnId)
        {
            if (!CheckPower(powerType))
            {
                CheckPowerFailWithWindowField(grid, columnId);
            }
        }



        protected void CheckPowerLendWithLinkButtonField(ExtAspNet.Grid grid, string columnId)
        {
            if (!CheckPowerLend())
            {
                CheckPowerFailWithLinkButtonField(grid, columnId);
            }
        }




        protected void CheckPowerGuestWithLinkButtonField(ExtAspNet.Grid grid, string columnId)
        {
            if (!CheckPowerGuest())
            {
                CheckPowerFailWithLinkButtonField(grid, columnId);
            }
        }

        protected void CheckPowerMenuAdminWithLinkButtonField(ExtAspNet.Grid grid, string columnId)
        {
            if (!CheckPowerMenuAdmin())
            {
                CheckPowerFailWithLinkButtonField(grid, columnId);
            }
        }
        protected void CheckPowerRestaurantWithLinkButtonField(ExtAspNet.Grid grid, string columnId)
        {
            if (!CheckPowerRestaurant())
            {
                CheckPowerFailWithLinkButtonField(grid, columnId);
            }
        }

        protected void CheckPowerDutyStoneWithLinkButtonField(ExtAspNet.Grid grid, string columnId)
        {
            if (!CheckPowerDutyStone())
            {
                CheckPowerFailWithLinkButtonField(grid, columnId);
            }
        }
        protected void CheckPowerDutyComWithLinkButtonField(ExtAspNet.Grid grid, string columnId)
        {
            if (!CheckPowerDutyCom())
            {
                CheckPowerFailWithLinkButtonField(grid, columnId);
            }
        }

        protected void CheckPowerDutyRestaurantWithLinkButtonField(ExtAspNet.Grid grid, string columnId)
        {
            if (!CheckPowerDutyRestaurant())
            {
                CheckPowerFailWithLinkButtonField(grid, columnId);
            }
        }

        #endregion

        #region Power Alert

        //protected void CheckPowerWithAlert(ModulePowerType powerType)
        //{
        //    if (!CheckPower(powerType))
        //    {
        //        CheckPowerFailWithAlert();
        //    }
        //}


        //protected void CheckPowerNewWithAlert()
        //{
        //    if (!CheckPowerNew())
        //    {
        //        CheckPowerFailWithAlert();
        //    }
        //}

        //protected void CheckPowerEditWithAlert()
        //{
        //    if (!CheckPowerEdit())
        //    {
        //        CheckPowerFailWithAlert();
        //    }
        //}

        //protected void CheckPowerDeleteWithAlert()
        //{
        //    if (!CheckPowerDelete())
        //    {
        //        CheckPowerFailWithAlert();
        //    }
        //} 

        #endregion

        #endregion
      
        public string SaveExcel(DataTable dt, string SheetName)
        {
            string stime = DateTime.Now.ToString(SheetName);
            string FileName = DateTime.Now.ToString(SheetName) + ".xls";
            //string sShowPath = ConfigurationManager.AppSettings["Website"] + @"Temp/" + stime + @"/" + FileName;
            string sShowPath = @"/Temp/" + stime + @"/" + FileName;
            string sPath = @Request.PhysicalApplicationPath + @"Temp\" + stime;
            if (!Directory.Exists(sPath))
                Directory.CreateDirectory(sPath);

            FileName = sPath + @"/" + FileName;
            if (File.Exists(FileName))
                File.Delete(FileName);
            try
            {
                string ConnStr;
                ConnStr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=\"" + FileName + "\";Extended Properties=\"Excel 8.0;HDR=YES\"";

                OleDbConnection conn_excel = new OleDbConnection();
                conn_excel.ConnectionString = ConnStr;

                OleDbCommand cmd_excel = new OleDbCommand();

                string sql;
                sql = SqlCreate(dt, SheetName);

                conn_excel.Open();
                cmd_excel.Connection = conn_excel;
                cmd_excel.CommandText = sql;
                cmd_excel.ExecuteNonQuery();

                conn_excel.Close();

                OleDbDataAdapter da_excel = new OleDbDataAdapter("Select * From [" + SheetName + "$]", conn_excel);
                DataTable dt_excel = new DataTable();
                da_excel.Fill(dt_excel);

                da_excel.InsertCommand = SqlInsert(SheetName, dt, conn_excel);

                DataRow dr_excel;
                string ColumnName;

                foreach (DataRow dr in dt.Rows)
                {
                    dr_excel = dt_excel.NewRow();

                    foreach (DataColumn dc in dt.Columns)
                    {
                        ColumnName = dc.ColumnName;
                        dr_excel[ColumnName] = dr[ColumnName];

                    }
                    dt_excel.Rows.Add(dr_excel);

                }

                da_excel.Update(dt_excel);
                conn_excel.Close();
            }
            catch (Exception ex)
            {
                //Utilities.Logger.LogNotifier.Log(LogWriter.LogType.ALL, string.Format("ERROR:  导出Excel出错：{0}", ex.Message));
                sShowPath = "";
            }
            return sShowPath;
        }
        private string SqlCreate(DataTable dt, string SheetName)
        {
            string sql;

            sql = "CREATE TABLE [" + SheetName + "] (";

            foreach (DataColumn dc in dt.Columns)
            {
                sql += "[" + dc.ColumnName + "] " + GetDataType(dc.DataType) + " ,";
            }

            //sql = "CREATE TABLE [" + SheetName + "] (";

            //foreach (C1.Win.C1TrueDBGrid.C1DataColumn dc in grid.Columns)
            //{
            //    sql += "[" + dc.Caption + "] " + GetDataType(dc.DataType) + ",";
            //}
            //sql = sql.Substring(0, sql.Length - 1);
            //sql += ")";

            sql = sql.Substring(0, sql.Length - 1);
            sql += ")";

            return sql;
        }


        // 生成 InsertCommand 并设置参数
        private OleDbCommand SqlInsert(string SheetName, DataTable dt, OleDbConnection conn_excel)
        {
            OleDbCommand i;
            string sql;

            sql = "INSERT INTO [" + SheetName + "$] (";
            foreach (DataColumn dc in dt.Columns)
            {
                sql += "[" + dc.ColumnName + "] ";
                sql += ",";
            }
            sql = sql.Substring(0, sql.Length - 1);
            sql += ") VALUES (";
            foreach (DataColumn dc in dt.Columns)
            {
                sql += "?,";
            }
            sql = sql.Substring(0, sql.Length - 1);
            sql += ")";

            i = new OleDbCommand(sql, conn_excel);

            foreach (DataColumn dc in dt.Columns)
            {
                i.Parameters.Add("@" + dc.Caption, StringToOleDbType(dc.DataType), 0, dc.Caption);
            }

            return i;
        }
        private string GetDataType(Type i)
        {
            string s;

            switch (i.Name)
            {
                case "String":
                    s = "Char";
                    break;
                case "Int32":
                    s = "Int";
                    break;
                case "Int64":
                    s = "Int";
                    break;
                case "Int16":
                    s = "Int";
                    break;
                case "Double":
                    s = "Double";
                    break;
                case "Decimal":
                    s = "Double";
                    break;
                default:
                    s = "Char";
                    break;

            }
            return s;
        }
        private OleDbType StringToOleDbType(Type i)
        {
            OleDbType s;

            switch (i.Name)
            {
                case "String":
                    s = OleDbType.Char;
                    break;
                case "Int32":
                    s = OleDbType.Integer;
                    break;
                case "Int64":
                    s = OleDbType.Integer;
                    break;
                case "Int16":
                    s = OleDbType.Integer;
                    break;
                case "Double":
                    s = OleDbType.Double;
                    break;
                case "Decimal":
                    s = OleDbType.Decimal;
                    break;
                default:
                    s = OleDbType.Char;
                    break;

            }
            return s;

        }
        public DataSet ImportExcel(String filePath)
        {
            try
            {
                string strConn;
                if (Path.GetExtension(filePath) == ".xlsx")
                    strConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filePath + ";Extended Properties=\"Excel 12.0;HDR=YES\"";
                else
                    strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filePath + ";Extended Properties='Excel 8.0;HDR=False;IMEX=1'";
                OleDbConnection OleConn = new OleDbConnection(strConn);
                OleConn.Open();
                string tableName = null;
                System.Data.DataTable table = OleConn.GetOleDbSchemaTable(System.Data.OleDb.OleDbSchemaGuid.Tables, null);
                for (int i = 0; i < table.Rows.Count; i++)
                {
                    if (table.Rows[i]["TABLE_NAME"].ToString().EndsWith("$"))
                        tableName = table.Rows[i]["TABLE_NAME"].ToString();
                }
                //string tableName = table.Rows[0]["Table_Name"].ToString();

                String sql = "SELECT * FROM [" + tableName + "]";//可是更改Sheet名称，比如sheet2，等等   

                OleDbDataAdapter OleDaExcel = new OleDbDataAdapter(sql, OleConn);
                DataSet OleDsExcle = new DataSet();
                OleDaExcel.Fill(OleDsExcle, tableName);
                OleConn.Close();
                //for (int i = 0; i < OleDsExcle.Tables[0].Rows.Count; i++)
                //{
                //    string etc = OleDsExcle.Tables[0].Rows[i][0] is DBNull ? "" : OleDsExcle.Tables[0].Rows[i][0].ToString();
                //    if (!string.IsNullOrEmpty(etc))
                //    {
                //        ms = new MS()
                //        {
                //            Etc = etc,
                //            CreateDate = OleDsExcle.Tables[0].Rows[i][1] is DBNull ? "" : OleDsExcle.Tables[0].Rows[i][1].ToString(),
                //            OralName = OleDsExcle.Tables[0].Rows[i][2] is DBNull ? "" : OleDsExcle.Tables[0].Rows[i][2].ToString(),
                //            Rater = OleDsExcle.Tables[0].Rows[i][3] is DBNull ? "" : OleDsExcle.Tables[0].Rows[i][3].ToString(),
                //            Score = OleDsExcle.Tables[0].Rows[i][4] is DBNull ? 0 : Convert.ToDouble(OleDsExcle.Tables[0].Rows[i][4]),
                //        };
                //        list.Add(ms);
                //    }
                //}
                //return list;
                return OleDsExcle;
            }
            catch (Exception err)
            {
                throw err;
            }
        }
    }
}